import type { PageInfo } from '@wlydfe/pro-ui'
import type { BasePageReq, BaseRes } from '@wlydfe/service'
import { omit } from 'lodash-es'

interface ListQueryOptions<T = any, P = Record<string, any>> {
  defaultPageSize?: number
  transformQuery?: (query: Partial<T & P>) => Partial<T & P>
  transformData?: (data: T[]) => T[]
}

/**
 * 分页查询
 *
 * @param param 分页参数
 * @param param.filterModel 分页过滤条件
 * @param param.fetchData 分页查询接口
 * @param param.options 分页查询配置
 * @returns 分页查询结果
 */
export const usePage = <T = any, P = Recordable>({
  filterModel = {},
  fetchData,
  options = {},
}: {
  filterModel?: Partial<T & P>
  fetchData: (params: BasePageReq<Partial<T & P>>) => Promise<BaseRes<T[]>>
  options?: ListQueryOptions<T, P>
}) => {
  const { defaultPageSize = 20, transformQuery, transformData } = options
  // const queryParams: BasePageReq<Partial<T & P>> = {
  //   currentPage: 1,
  //   pageLength: 20,
  //   filterModel,
  //   countTotal: true,
  // }

  const resultData = ref<T[]>([])
  const getList = async (query: Partial<PageInfo> & Record<string, any>) => {
    const queryParams: BasePageReq<Partial<T & P>> = {
      currentPage: 1,
      pageLength: 20,
      filterModel,
      countTotal: true,
    }
    // 更新分页参数
    queryParams.currentPage = query.page ?? 1
    queryParams.pageLength = query.pageSize ?? defaultPageSize

    const _filterModel: Partial<T & P> = {
      ...queryParams.filterModel,
      ...omit(query, ['page', 'pageSize', 'value']),
    }

    // 允许外部转换查询参数
    queryParams.filterModel = transformQuery ? transformQuery(_filterModel) : _filterModel

    // 调用接口获取数据
    const { succeed, model, total } = await fetchData(queryParams)
    let data = succeed ? model : []

    // 允许外部转换返回数据
    if (transformData && data.length > 0) {
      data = transformData(data)
    }

    resultData.value = data
    return {
      data: resultData.value,
      total: total ?? 0,
    }
  }

  return {
    defaultPageSize,
    resultData,
    getList,
  }
}
